{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-04-25T03:31:29.874978Z",
     "start_time": "2025-04-25T03:31:29.836037Z"
    }
   },
   "source": [
    "import numpy as np\n",
    "from scipy.stats import norm\n",
    "\n",
    "\n",
    "class GaussianNaiveBayes:\n",
    "    def fit(self, X, y):\n",
    "        self.classes = np.unique(y)\n",
    "        self.n_classes = len(self.classes)\n",
    "        self.n_features = X.shape[1]\n",
    "        self.priors = np.zeros(self.n_classes)\n",
    "        self.means = np.zeros((self.n_classes, self.n_features))\n",
    "        self.variances = np.zeros((self.n_classes, self.n_features))\n",
    "\n",
    "        for i, c in enumerate(self.classes):\n",
    "            X_c = X[y == c]\n",
    "            self.priors[i] = X_c.shape[0] / X.shape[0]\n",
    "            self.means[i, :] = X_c.mean(axis=0)\n",
    "            self.variances[i, :] = X_c.var(axis=0)\n",
    "\n",
    "    def predict(self, X):\n",
    "        posteriors = []\n",
    "        for sample in X:\n",
    "            posterior = []\n",
    "            for i in range(self.n_classes):\n",
    "                prior = np.log(self.priors[i])\n",
    "                likelihood = np.sum(norm.logpdf(sample, self.means[i], np.sqrt(self.variances[i])))\n",
    "                posterior.append(prior + likelihood)\n",
    "            posteriors.append(posterior)\n",
    "        posteriors = np.array(posteriors)\n",
    "        return self.classes[np.argmax(posteriors, axis=1)]\n",
    "\n",
    "\n",
    "# 示例使用\n",
    "if __name__ == \"__main__\":\n",
    "    X = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]])\n",
    "    y = np.array([0, 0, 0, 1, 1, 1])\n",
    "\n",
    "    model = GaussianNaiveBayes()\n",
    "    model.fit(X, y)\n",
    "\n",
    "    new_X = np.array([[2.5, 3.5], [5.5, 6.5]])\n",
    "    predictions = model.predict(new_X)\n",
    "    print(\"预测结果:\", predictions)\n",
    "    "
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预测结果: [0 1]\n"
     ]
    }
   ],
   "execution_count": 1
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
